package model.components.graphs.graph;

import java.util.ArrayList;
import java.util.List;

import model.components.links.link.Link;
import model.components.nodes.node.Node;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
import edu.uci.ics.jung.graph.UndirectedGraph;
import edu.uci.ics.jung.graph.util.Pair;

@SuppressWarnings("serial")
public class SparseMultigraphGraph extends SparseMultigraph< Node, Link > implements UndirectedGraph< Node, Link >
{
	public Graph< Node, Link > getCopy()
	{
		SparseMultigraphGraph sparseMultigraphGraph = new SparseMultigraphGraph();
	
		for( Link link: this.getEdges() )
		{
			Pair< Node > endPoints = this.getEndpoints( link );
			
			Node firstNode = sparseMultigraphGraph.getNode( endPoints.getFirst().getNumber() );
			
			if( firstNode == null )
				firstNode = endPoints.getFirst().getCopy();
			
			Node secondNode = sparseMultigraphGraph.getNode( endPoints.getSecond().getNumber() );
			
			if( secondNode == null )
				secondNode = endPoints.getSecond().getCopy();
			
			sparseMultigraphGraph.addEdge( link.getCopy(), firstNode, secondNode );
		}
		
		return sparseMultigraphGraph;
	}

	private Node getNode( int identifier )
	{
		for( Node node: this.getVertices() )		
			if( node.getNumber() == identifier )
				return node;
		
		return null;
	}
	
	@Override
	public boolean addEdge( Link link, Node first, Node second )
	{
		return super.addEdge( link, first, second );
	}
	
	public void removeUnconnectedNodes()
	{
		List< Node > nodes = new ArrayList< Node >();
	
		for( Node node: this.getVertices() )
			if( this.degree( node ) == 0 )
				nodes.add( node );
		
		for( Node node: nodes )
			this.removeVertex( node );
	}
	
}
